<template>
  <div class="earth-page" id="earthContainer">

  </div>
</template>

<script type="text/ecmascript-6">
import * as THREE from 'three'
import * as Glow from '../../assets/js/glow.js'
import TWEEN from 'tween.js'
// const OrbitControls = require('three-orbit-controls')
const OrbitControls = require('three-orbit-controls')(THREE);

export default {
  data() {
    return {
      scene:null,
      camera:null,
      renderer: null,
      mesh: null,
      control:null,
      container:null,
      group:null,
      earth:null,
      spotLigth:null,
      earthGroup:null,
      startPoint:{
        x:3000,
        y:0,
        z:0
      },
      endPoint:{
        x:-3000,
        y:0,
        z:0
      },
      heightLimit:50,
      flyTime:8000,
      lineStyle:{
        color:0xffffff,
        linewidth:20
      }
    }
  },
  components: {

  },
  mounted () {
    this.init();
    this.render();
    // this.initWebSocket();
    this.animate();
    // window.addEventListener( 'click', this.onMouseClick, false )
  },
  destroyed () {
    window.removeEventListener('resize',this.onWindowResize);
  },
  methods: {
    init(){
      var _this=this;
      this.container = document.getElementById('earthContainer');
      //创建渲染器
      this.renderer = new THREE.WebGLRenderer({
        alpha: true,
        antialias: true,
        preserveDrawingBuffer: true
      })
      this.group = new THREE.Group();
      this.earthGroup=new THREE.Group();
      //设置像素比
      this.renderer.setPixelRatio( window.devicePixelRatio );
      //设置渲染器的宽高
      this.renderer.setSize(this.container.clientWidth, this.container.clientHeight);
      //添加到容器中
      this.container.appendChild(this.renderer.domElement);
      this.scene = new THREE.Scene();
      this.camera = new THREE.PerspectiveCamera(45, this.container.clientWidth/this.container.clientHeight, 1, 3000);
      //创建camera位置
      this.camera.position.set(-1600, 0, 600)
      this.camera.lookAt( 0, 0, 200 )
      //创建光源
      var DirectionalLight=new THREE.DirectionalLight(0xffffff, 0.8)
      DirectionalLight.position.set(-3000,600,-3000);
      this.group.add(DirectionalLight)
      //环境光
      let ambientLigth=this._createAmbientLight();
      //聚光灯
      // this.spotLigth=this._createSpotLight();
      // this.camera.add(this.spotLigth);
      this.group.add(ambientLigth);
      // this.group.add(spotLigth);
      this.scene.add(this.group);
      this.scene.add(this.earthGroup);
      // this.scene.add(this.spotLigth);

      //星空
      this._createStars();
      //地球
      this._createEarth();
      //设置阴影
      // this._createShadow();
      //创建大气层
      this._createCloud();
      // //创建光晕
      // this._createHalo();
      // this._createOutGlow();
      let aCurve = this._createFlyLine(this.startPoint, this.endPoint, this.heightLimit, this.flyTime, this.lineStyle)
      console.log(aCurve)
      this.earthGroup.add(aCurve)
      //创建轨道控制器 传入camera
      this.orbit = new OrbitControls( this.camera, this.renderer.domElement );
      this.orbit.update();

      window.addEventListener( 'resize', this.onWindowResize, false );
    },
    _createStars() {
        var starsGeometry = new THREE.Geometry();
        for (var i = 0; i < 2000; i ++) {
            var starVector = new THREE.Vector3(
                THREE.Math.randFloatSpread(2000),
                THREE.Math.randFloatSpread(2000),
                THREE.Math.randFloatSpread(2000)
            );
            starsGeometry.vertices.push(starVector);
        }
        var starsMaterial = new THREE.PointsMaterial({color: 0x888888})
        var starsPoint = new THREE.Points(starsGeometry, starsMaterial);
        this.group.add(starsPoint);
    },
    _createEarth() {
      var _this=this;
      let earthTexture=this.getTextUre('static/images/earth4.jpg');
      let earthBumpTexture=this.getTextUre('static/images/earth_bump.jpg');
      let earthSpecTexture= this.getTextUre('static/images/earth_spec.jpg')
      var globeGgeometry = new THREE.SphereGeometry(200, 100, 100);
      var globeMaterial = new THREE.MeshStandardMaterial(
        {
          map: earthTexture,
          bumpMap:earthBumpTexture,
          bumpScale: 0.15,
          specularMap:earthSpecTexture,
          specular: new THREE.Color('#909090'),
          shininess: 5,
          transparent: true
        }
      );
      _this.earth = new THREE.Mesh(globeGgeometry, globeMaterial);
      _this.earthGroup.add(_this.earth);
    },
    getTextUre(url){
      let loader =new THREE.TextureLoader();
      return loader.load(url);
    },
    _createAmbientLight () {
      return new THREE.AmbientLight(0xffffff, 0.3)
    },
    _createSpotLight () {
      let spotLight = new THREE.SpotLight(0xffffff,20)
      spotLight.position.set(-3300, 300,-30)
      spotLight.angle = 0.2
      spotLight.castShadow = false
      spotLight.penumbra = 0.8
      spotLight.distance = 3300
      spotLight.decay = 1
      // spotLight.target = this.earth||null;
      spotLight.shadow.camera.near = 2000
      spotLight.shadow.camera.far = 300
      spotLight.shadow.camera.fov = 30
      // spotLight.shadow.mapSize.height = 1024
      // spotLight.shadow.mapSize.width = 1024
      spotLight.shadowCameraVisible = true;//开启调试模式
      return spotLight
    },
    _createCloud(){
      var _this=this;
      let globeTextureLoader = new THREE.TextureLoader();
      globeTextureLoader.crossOrigin = '';
      globeTextureLoader.load('static/images/earth_cloud.png', function (texture) {
          var globeGgeometry = new THREE.SphereGeometry(210, 110, 110);
          var globeMaterial = new THREE.MeshPhongMaterial(
            {
              map: texture,
              transparent: true,
              opacity: 1,
              blending: THREE.AdditiveBlending
            }
          );
          var globeMesh = new THREE.Mesh(globeGgeometry, globeMaterial);
          _this.earthGroup.add(globeMesh);
      });
    },
    // _createHalo(){
    //   let sphere = new THREE.SphereGeometry(200, 100, 100)
    //   let material = this.createFlowMaterial()
    //   let glowSphere = new Mesh(sphere, material)
    //   glowSphere.material.side = BackSide
    //   glowSphere.material.transparent = false
    //   glowSphere.scale.x = glowSphere.scale.y = glowSphere.scale.z = 1.3
    //   _this.group.add(globeMesh);
    // },
    _createFlyLine(startPoint,endPoint,heightLimit,flyTime,lineStyle){
      var middleCurvePositionX = (startPoint.x + endPoint.x) / 2
        var middleCurvePositionY = heightLimit
        var middleCurvePositionZ = (startPoint.z + endPoint.z) / 2

        var curveData = new THREE.CatmullRomCurve3([
            new THREE.Vector3(startPoint.x, startPoint.y, startPoint.z),
            new THREE.Vector3(middleCurvePositionX, middleCurvePositionY, middleCurvePositionZ),
            new THREE.Vector3(endPoint.x, endPoint.y, endPoint.z)
        ])
        var curveModelData = curveData.getPoints(50)

        var curveGeometry = new THREE.Geometry()
        curveGeometry.vertices = curveModelData.slice(0, 1)
        var curveMaterial = new THREE.LineBasicMaterial({color: lineStyle.color, linewidth: lineStyle.linewidth})
        var curve = new THREE.Line(curveGeometry, curveMaterial)


        var tween = new TWEEN.Tween({endPointIndex:1})
            .to({endPointIndex:50}, flyTime)

        tween.onUpdate(tweenHandler)

        tween.start()

        return curve

        function tweenHandler() {
            var endPointIndex = Math.ceil(this.endPointIndex)

            var curvePartialData = new THREE.CatmullRomCurve3(curveModelData.slice(0, endPointIndex))
            curve.geometry.vertices = curvePartialData.getPoints(50)
            curve.geometry.verticesNeedUpdate = true
        }
    },
    onWindowResize() {
				this.camera.aspect = window.innerWidth / window.innerHeight;
				this.camera.updateProjectionMatrix();
				this.renderer.setSize( window.innerWidth, window.innerHeight );
				this.render();
    },
    //渲染
    render() {
      this.earthGroup.rotation.y += 0.005;
      // this.earth.rotation.y -= 0.005
      this.renderer.render(this.scene, this.camera); // 结合场景和相机进行渲染，即用摄像机拍下此刻的场景
      requestAnimationFrame(this.render); // 让浏览器执行参数中的函数，不断循环（浏览器一个新的API）

    },
    //设置3d动态效果
    animate() {
        requestAnimationFrame(this.animate);
        // this.mesh.rotation.x += 0.01;
        // if(this.earth){
        //   this.earth.rotation.y += 0.002;
        // }
        // this.camera.position.x=this.camera.position.x+0.001;
        this.renderer.render(this.scene, this.camera);
    }
  }
}
</script>

<style scoped lang='scss'>
.earth-page{
  width: 100%;
  height: 100%;
  background: transparent;
}
</style>
